<template>
  <Dialog
    :title="dialogTitle"
    v-model="dialogVisible"
    :max-height="maxHeight"
    :width="width"
    append-to-body
    style="padding-bottom: 0px !important"
  >
    <el-container>
      <el-aside class="aside">
        <el-scrollbar :max-height="maxHeight" class="pr-20px">
          <div
            class="payment-item"
            v-for="(item, index) in state.payMethods.items"
            @click="selectPayMent(index)"
            :key="index"
            :class="{ 'payment-item-active': nowPaymentIndex == index || item.payStatus }"
          >
            <el-image :src="item.icon" class="icon ml-10px" />
            <el-text class="custom-text-18 ml-10px!" truncated> {{ item.assetsTitle }}</el-text>
            <div class="virtual_san" v-if="item.payStatus"></div>
            <div class="virtual_dui custom-text-18" v-if="item.payStatus">✓</div>
          </div>
        </el-scrollbar>
      </el-aside>
      <el-main class="main">
        <el-row class="payment-info">
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(state.orderInfo.price.totalPrice) }}</div
              >
              <div class="custom-text-18">订单金额</div>
            </div>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(state.orderInfo.price.paidPrice) }}</div
              >
              <div class="custom-text-18">已付金额</div>
            </div>
          </el-col>
          <el-col :xs="8" :sm="8" :md="8" :lg="8" :xl="8">
            <div class="text-center">
              <div class="custom-text-24 c-[var(--el-color-primary)]!"
                >￥{{ fenToYuan(state.orderInfo.price.payPrice) }}</div
              >
              <div class="custom-text-18">待支付金额</div>
            </div>
          </el-col>
        </el-row>
        <div class="payment-operation">
          <div class="flex-1">
            <div class="mt-10px">
              <el-input
                v-model="nowPayment.usePayBalance"
                class="payment-input custom-text-44"
                :disabled="nowPayment.payStatus"
                ref="inputRef"
                :formatter="(value: any) => verifyNumberIntegerAndFloat(value)"
              >
                <template #prepend>
                  <div class="flex items-center">
                    <el-image :src="collection" class="collection-icon" />
                    <span class="custom-text-22 ml-5px">优惠后金额</span>
                  </div>
                </template>
              </el-input>
            </div>
            <div class="flex justify-between w-100% items-center mt-10px">
              <div class="custom-text-20">
                <span v-if="!state.isHideLowePrice">
                  最低限价: {{ fenToYuan(state.orderInfo.price.lowerPrice) }}
                </span>
                <span v-if="state.isHideLowePrice"> 最低限价****** </span>
                <Icon
                  :icon="state.isHideLowePrice ? 'ep:view' : 'ep:hide'"
                  class="ml-10px"
                  @click="
                    () => {
                      state.isHideLowePrice = !state.isHideLowePrice
                    }
                  "
                />
              </div>

              <div class="flex">
                <el-text type="primary" class="custom-text-18 mr-5px!" @click="onHandleCancel">
                  取消优惠
                </el-text>
              </div>
            </div>
          </div>
          <div class="flex items-center mt-10px justify-center">
            <DigitKeyboard
              ref="DigitKeyboardRef"
              @on-change="onInputChange"
              @on-confirm="onConfirm"
              @on-cancel="onHandleCancel"
              :disabled="nowPayment.payStatus"
              :input="nowPayment.usePayBalance"
            />
          </div>
        </div>
      </el-main>
    </el-container>

    <template #footer v-if="slots.footer">
      <slot name="footer"></slot>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
// 储值卡弹窗
import { defineAsyncComponent, ref, useSlots } from 'vue'
import collection from '@/assets/svgs/collection.svg'

import { fenToYuan, yuanToFen } from '@/utils'

const DigitKeyboard = defineAsyncComponent(() => import('./digitKeyBoard.vue'))
const slots = useSlots()
import { propTypes } from '@/utils/propTypes'
const props = defineProps({
  orderInfo: propTypes.object, //订单信息
  paymentMap: propTypes.array
})
// 检测支付环境
const state = reactive({
  orderInfo: computed(() => {
    return props.orderInfo
  }), // 支付单信息
  payMethods: computed(() => {
    return props.paymentMap.find((ele: any) => {
      return ele.classify == nowPaymenthds.value.classify
    })
  }) as any, // 可选的支付方式
  payment: '', // 选中的支付方式
  payOrderList: [] as any, //当前支付方式的支付流水号
  activeName: '', //当前选中的支付方式
  isHideLowePrice: true
})

const nowPaymenthds = ref() //当前使用的资产

const DigitKeyboardRef = ref()
const onInputChange = (input: any) => {
  nowPayment.value.usePayBalance = input
} //输入发生变化时
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('整单优惠') // 弹窗的标题
const width = ref('715px') //宽度
const maxHeight = ref('545px')
// 选择支付方式
const emit = defineEmits(['handleUsePaymentPay'])

// 监听支付方式的变化
watch(
  () => props.paymentMap,
  () => {
    console.log(nowPayment.value.payStatus)
    if (nowPaymentIndex.value == undefined) {
      return
    }

    nowPayment.value = state.payMethods.items[nowPaymentIndex.value]
    if (nowPayment.value.payStatus) {
      nowPayment.value.usePayBalance = fenToYuan(nowPayment.value.paybalance)
    } else {
      nowPayment.value.usePayBalance = ''
    }
    setKeyBoardLayout()
  }
)
const nowPayment = ref<any>({})
const nowPaymentIndex = ref<any>() //当前支付方式的下标
const inputRef = ref()
const selectPayMent = (index: any) => {
  nowPaymentIndex.value = index
  let item = state.payMethods.items[nowPaymentIndex.value]
  nowPayment.value = item
  if (item.payStatus) {
    nowPayment.value.usePayBalance = fenToYuan(nowPayment.value.paybalance)
  } else {
    nowPayment.value.usePayBalance = ''
  }
  setKeyBoardLayout()
}
const setKeyBoardLayout = () => {
  if (nowPayment.value.payStatus) {
    setTimeout(() => {
      DigitKeyboardRef.value.setKeyBoardLayout('cancel')
    }, 100)
  } else {
    setTimeout(() => {
      DigitKeyboardRef.value.setKeyBoardLayout('default')
    }, 100)
  }
}
const onHandleCancel = () => {
  let item = state.payMethods.items[nowPaymentIndex.value]
  item.payStatus = false

  emit('handleUsePaymentPay', item, nowPaymenthds.value.classify)
}

/** 打开弹窗 */

const open = async (payMethods: any) => {
  dialogVisible.value = true
  nowPaymenthds.value = payMethods
  await setNowPayment()
}
const setNowPayment = () => {
  console.log(123)
  let selectPayMentIndexs = [] as any
  state.payMethods.items.forEach((element, index) => {
    if (element.payStatus) {
      selectPayMentIndexs.push(index)
    }
  })
  console.log(selectPayMentIndexs)

  if (selectPayMentIndexs.length == 0) {
    nowPayment.value = {}
    selectPayMent(0)
  } else {
    nowPaymentIndex.value = selectPayMentIndexs[0]
    nowPayment.value = state.payMethods.items[nowPaymentIndex.value]
    state.activeName = nowPayment.value.assetsTitle
    nowPayment.value.usePayBalance = fenToYuan(nowPayment.value.paybalance)
  }
} //设置当前选中的支付方式

const close = async () => {
  dialogVisible.value = false
}

defineExpose({ open, close }) // 提供 open 方法，用于打开弹窗

const message = useMessage() // 消息弹窗
import { verifyNumberIntegerAndFloat } from '@/utils/formatter'
/** 购物车信息 */

const onConfirm = () => {
  if (!nowPayment.value.usePayBalance) {
    message.error('优惠后金额不能为空')
    return
  }

  nowPayment.value.paybalance = yuanToFen(nowPayment.value.usePayBalance)

  if (Number(nowPayment.value.paybalance) < Number(state.orderInfo.price.lowerPrice)) {
    message.error('优惠后金额必须大于最低限价')
    return
  }
  nowPayment.value.payStatus = true
  emit('handleUsePaymentPay', nowPayment.value, nowPaymenthds.value.classify)
  close()
} //确认当前支付方式
</script>
<style lang="scss" scoped>
:deep(.el-input.is-disabled .el-input__wrapper) {
  background: transparent !important;
}
.aside {
  width: 210px;
}

.main {
  width: 470px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

:deep(.el-main) {
  --el-main-padding: 0px !important;
  width: 470px;
}

// .payment-item {
//   width: 190px;
//   height: 70px;
//   background: url('@/assets/imgs/payCashier/paymentBg.png') center no-repeat;
//   background-size: 100% 100%;
//   cursor: pointer;
//   display: flex;
//   align-items: center;
//   margin-bottom: 10px;
//   .icon {
//     width: 24px;
//     height: 24px;
//   }

//   .virtual_san {
//     display: none;
//   }

//   .virtual_dui {
//     display: none;
//   }

//   &-active {
//     background: url('@/assets/imgs/payCashier/paymentActive.png') center no-repeat;
//     background-size: 100% 100%;
//     position: relative;

//     .virtual_san {
//       display: block;
//       position: absolute;
//       bottom: 0;
//       right: 0;
//       width: 0;
//       height: 0;
//       border-bottom: 35px solid var(--el-color-primary);
//       border-left: 35px solid transparent;
//       border-bottom-right-radius: 5px;
//     }

//     .virtual_dui {
//       display: block;

//       position: absolute;
//       bottom: -2px;
//       right: 5px;
//       color: #fff;
//       font-family: system-ui;
//     }
//   }
// }
// .payment-info {
//   width: 470px;
//   height: 85px;
//   display: flex;
//   flex-direction: row;
//   justify-content: space-between;
//   align-items: center;
//   background-color: var(--app-content-bg-color) !important;
//   border-radius: 5px;

//   &-item {
//     width: 117.5px;
//     text-align: center;
//   }
// }
// .dark .payment-info {
//   width: 470px;
//   height: 85px;
//   display: flex;
//   flex-direction: row;
//   justify-content: space-between;
//   align-items: center;
//   background-color: var(--el-bg-color-overlay) !important;

//   border-radius: 5px;

//   &-item {
//     width: 117.5px;
//     text-align: center;
//   }
// }
// .payment-operation {
//   flex: 1;
//   display: flex;
//   flex-direction: column;
//   justify-content: space-between;
// }
.payment-input {
  width: 470px;

  height: 60px;

  :deep(.el-input-group__prepend) {
    background: var(--el-color-primary);
    color: #fff;
    padding: 0 10px;
    box-shadow: none;
  }

  :deep(.el-input__inner) {
    --el-input-inner-height: 48px;
  }
  :deep(.el-input-group__append) {
    background: var(--el-color-primary);
    color: #fff;
    padding: 0 10px;
    box-shadow: none;
  }
}

:deep(.el-divider--horizontal) {
  margin: 20px 0 13px 0;
}

.collection-icon {
  width: 24px;
  height: 24px;
}
</style>
